package com.example.echoewish.ui.my_activity.login_and_register_activity;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.echoewish.econstant.Constant;
import com.example.echoewish.econstant.UserInfo;
import com.example.echoewish.pojo.User;
import com.example.echoewish.repository.UserMessageRepository;
import com.example.echoewish.util.LogUtil;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LoginAndRegisterViewModel extends ViewModel{

    public MutableLiveData<Integer> userIdMutableLiveData;
    public MutableLiveData<String> stringResponseMutableLiveData;
    public MutableLiveData<User> newUserMutableLiveData;

    public LoginAndRegisterViewModel()
    {
        userIdMutableLiveData =new MutableLiveData<>();
        stringResponseMutableLiveData=new MutableLiveData<>();
        newUserMutableLiveData=new MutableLiveData<>();
    }

    public void loginOn()
    {
        UserMessageRepository.getInstance().loginOn(newUserMutableLiveData.getValue().account,
                newUserMutableLiveData.getValue().password,new LoginOnCallBack());
    }

    public void getUserInfo()
    {
        UserMessageRepository.getInstance().queryUserByUserId(userIdMutableLiveData.getValue(),new GetUserInfoCallBack());
    }

    private class LoginOnCallBack implements Callback<ResponseBody>
    {

        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            try {
                userIdMutableLiveData.postValue(Integer.valueOf(response.body().string()));
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            new LogUtil().w(LogUtil.CALLBACK_TAG,"用户登录 回调失败"+t);
            userIdMutableLiveData.postValue(-1);
        }
    }

    private class GetUserInfoCallBack implements Callback<User>
    {

        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            User user=response.body();
            UserInfo.getInstance().account=user.account;
            UserInfo.getInstance().password=user.password;
            UserInfo.getInstance().name=user.name;
            UserInfo.getInstance().campus=user.campus;
            UserInfo.getInstance().grade=user.grade;
            UserInfo.getInstance().sex=user.sex;
            UserInfo.getInstance().headImage=user.headImage;
        }

        @Override
        public void onFailure(Call<User> call, Throwable t) {
            new LogUtil().w(LogUtil.CALLBACK_TAG,"获取用户信息 回到未登录状态 回调失败"+t);
            UserInfo.getInstance().IsLogin=false;
            UserInfo.getInstance().UserId=-1;
        }
    }
}
